package org.edu.modules.classSwitch.controller;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.CommonAPI;
import org.edu.common.api.vo.Result;
import org.edu.common.system.api.ISysBaseAPI;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.DateUtils;
import org.edu.common.util.oConvertUtils;
import org.edu.modules.classSchedule.entity.VeJwPaike;
import org.edu.modules.classSchedule.service.IVeJwPaikeService;
import org.edu.modules.classSwitch.entity.VeJwTiaoke;
import org.edu.modules.classSwitch.entity.VeJwTiaokeDto;
import org.edu.modules.classSwitch.service.IVeJwTiaokeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.edu.modules.jxrw.entity.VeJwPkmx;
import org.edu.modules.jxrw.service.IVeJwPkmxService;
import org.edu.modules.scheduleCommon.entity.VeBaseAppUser;
import org.edu.modules.scheduleCommon.entity.VeBaseTeacher;
import org.edu.modules.scheduleCommon.service.VeBaseAppUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.edu.common.system.base.controller.BaseController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.edu.common.aspect.annotation.AutoLog;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @Description: 调课信息
 * @Author:
 * @Date: 2021-05-13
 * @Version: V1.0
 */
@Api(tags = "调课信息")
@RestController
@RequestMapping("/classSwitch/veJwTiaoke")
@Slf4j
public class VeJwTiaokeController extends BaseController<VeJwTiaoke, IVeJwTiaokeService> {

    @Autowired
    private IVeJwTiaokeService veJwTiaokeService;

    @Autowired
    private IVeJwPaikeService veJwPaikeService;

    @Autowired
    private IVeJwPkmxService veJwPkmxService;

    @Autowired
    private VeBaseAppUserService veBaseAppUserService;


    /**
     * 分页查询
     *
     * @param veJwTiaoke
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "调课信息-分页查询")
    @ApiOperation(value = "分页查询", notes = "调课信息-分页查询")
    @PostMapping(value = "/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skxzbdm", value = "教学班代码", required = false),
            @ApiImplicitParam(name = "jsjgh", value = "教师工号", required = false),
            @ApiImplicitParam(name = "kcmc", value = "课程名称", required = false),
            @ApiImplicitParam(name = "verifyStatus", value = "审核状态", required = false),
            @ApiImplicitParam(name = "currentUser", value = "1-当前用户，空-不限", required = false)
    })
    public Result<?> queryPageList(@ApiIgnore VeJwTiaoke veJwTiaoke,
                                   String skxzbdm,      //教学班代码
                                   String jsjgh,        //教师工号
                                   String kcmc,         //课程名称
                                   String verifyStatus, //审核状态
                                   String currentUser,  //当前用户
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
//		QueryWrapper<VeJwTiaoke> queryWrapper = QueryGenerator.initQueryWrapper(veJwTiaoke, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        QueryWrapper<VeJwTiaoke> queryWrapper = new QueryWrapper<>();
        //根据用户id查用户信息
        VeBaseAppUser appUser = veBaseAppUserService.getVeBaseAppUserById(loginUser.getId());
        if (appUser.getUserType().contains("1")) {
            //如果用户类型是1，为教师账号
            queryWrapper.eq("t.jsjgh", appUser.getUserId());
        }
        if (skxzbdm != null && !skxzbdm.equals("")) {
            queryWrapper.eq("t.skxzbdm", skxzbdm);
        }
        if (jsjgh != null && !jsjgh.equals("")) {
            queryWrapper.eq("t.jsjgh", jsjgh);
        }
        if (kcmc != null && !kcmc.equals("")) {
            queryWrapper.like("k.kcmc", kcmc);
        }
        if (verifyStatus != null && !verifyStatus.equals("")) {
            queryWrapper.eq("t.verify_status", verifyStatus);
        }
        if (currentUser != null && currentUser.equals("1")) {

        }
        Page<Map<String, Object>> page = new Page<Map<String, Object>>(pageNo, pageSize);
        IPage<Map<String, Object>> pageList = veJwTiaokeService.pageMaps(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "调课信息-通过id查询")
    @ApiOperation(value = "通过id查询", notes = "调课信息-通过id查询")
    @PostMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeJwTiaoke veJwTiaoke = veJwTiaokeService.getById(id);
        if (veJwTiaoke == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(veJwTiaoke);
    }

    /**
     * 新增信息
     *
     * @param veJwTiaoke
     * @return
     */
    @AutoLog(value = "调课信息-新增信息")
    @ApiOperation(value = "新增信息", notes = "调课信息-新增信息")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeJwTiaoke veJwTiaoke) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        veJwTiaoke.setJsjgh(loginUser.getUsername());

        VeJwPaike veJwPaike = veJwPaikeService.getById(veJwTiaoke.getPkid());
        if (veJwPaike == null) {
            return Result.error("排课信息缺失");
        }
        veJwTiaoke.setSkxzbdm(veJwTiaoke.getJxbid() + "");
        //判断该班级调课后的时间是否已被其他课程占据
        Set<Integer> pkIdList = new HashSet<>();
        LambdaQueryWrapper<VeJwPaike> paikeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        paikeLambdaQueryWrapper.eq(VeJwPaike::getJxbid, veJwPaike.getJxbid());
        List<VeJwPaike> veJwPaikeList = veJwPaikeService.list(paikeLambdaQueryWrapper);
        if (veJwPaikeList != null && veJwPaikeList.size() > 0) {
            pkIdList = veJwPaikeList.stream().map(VeJwPaike::getId).collect(Collectors.toSet());
            LambdaQueryWrapper<VeJwPkmx> veJwPkmxLambdaQueryWrapper = new LambdaQueryWrapper<>();
            veJwPkmxLambdaQueryWrapper.eq(VeJwPkmx::getWeek, veJwTiaoke.getXweek());
            veJwPkmxLambdaQueryWrapper.eq(VeJwPkmx::getSection, veJwTiaoke.getXsection());
            veJwPkmxLambdaQueryWrapper.eq(VeJwPkmx::getSemid, veJwTiaoke.getSemid());
            veJwPkmxLambdaQueryWrapper.in(VeJwPkmx::getPkid, pkIdList);
            List<VeJwPkmx> veJwPkmxList = veJwPkmxService.list(veJwPkmxLambdaQueryWrapper);
            if (veJwPkmxList != null && veJwPkmxList.size() > 0) {
                return Result.error("该时间段是" + veJwPkmxList.get(0).getJsxm() + "老师的课");
            }
        }
        //判断申请调课的老师在调课后的时间是否有排课
        LambdaQueryWrapper<VeJwPkmx> veJwPkmxLambdaQueryWrapper = new LambdaQueryWrapper<>();
        veJwPkmxLambdaQueryWrapper.eq(VeJwPkmx::getWeek, veJwTiaoke.getXweek());
        veJwPkmxLambdaQueryWrapper.eq(VeJwPkmx::getSection, veJwTiaoke.getXsection());
        veJwPkmxLambdaQueryWrapper.eq(VeJwPkmx::getSemid, veJwTiaoke.getSemid());
        veJwPkmxLambdaQueryWrapper.in(VeJwPkmx::getTeacherid, veJwTiaoke.getTeacherid());
        List<VeJwPkmx> veJwPkmxList = veJwPkmxService.list(veJwPkmxLambdaQueryWrapper);
        if (veJwPkmxList != null && veJwPkmxList.size() > 0) {
            return Result.error("该时间段您已有安排课程");
        }
        if (veJwTiaokeService.save(veJwTiaoke)) {
            return Result.OK("添加成功！");
        }
        return Result.error("添加失败!");
    }

    /**
     * 修改信息
     *
     * @param veJwTiaokeDto
     * @return
     */
    @AutoLog(value = "调课信息-修改信息")
    @ApiOperation(value = "修改信息", notes = "调课信息-修改信息")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeJwTiaokeDto veJwTiaokeDto) throws ParseException {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        VeJwTiaoke veJwTiaoke = new VeJwTiaoke();
        BeanUtils.copyProperties(veJwTiaokeDto, veJwTiaoke);
        if (StringUtils.isNotBlank(veJwTiaokeDto.getYskrq())) {
            veJwTiaoke.setYskrq(Integer.parseInt(DateUtils.parseDate(veJwTiaokeDto.getYskrq(), "yyyy-MM-dd").getTime() / 1000 + ""));
        }
        if (StringUtils.isNotBlank(veJwTiaokeDto.getXskrq())) {
            veJwTiaoke.setXskrq(Integer.parseInt(DateUtils.parseDate(veJwTiaokeDto.getXskrq(), "yyyy-MM-dd").getTime() / 1000 + ""));
        }
        VeJwTiaoke oldVeJwTiaoke = veJwTiaokeService.getById(veJwTiaokeDto.getId());

        if (veJwTiaokeDto.getVerifyStatus() != null && !oldVeJwTiaoke.getVerifyStatus().equals(veJwTiaokeDto.getVerifyStatus())) {
            veJwTiaoke.setVerifyUser(loginUser.getUsername());
            veJwTiaoke.setVerifyTime(Integer.parseInt(new Date().getTime() / 1000 + ""));
        }
        if (veJwTiaokeService.updateById(veJwTiaoke)) {
            return Result.OK("编辑成功!");
        }
        return Result.error("编辑失败!");
    }

    /**
     * 发布信息
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "调课信息-审核通过")
    @PostMapping("pass")
    @ApiOperation(value = "批量审核通过", notes = "调课信息-审核通过")
    public Result<?> pass(@RequestParam(name = "ids", required = true) String ids) {
        if (this.veJwTiaokeService.changeStatusByIds(ids.split(","), 1) > 0) {
            return Result.OK("操作成功!");
        }
        return Result.error("操作失败");
    }

    /**
     * 取消发布信息
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "调课信息-审核不通过")
    @PostMapping("noPass")
    @ApiOperation(value = "批量审核不通过", notes = "调课信息-审核不通过")
    public Result<?> noPass(@RequestParam(name = "ids", required = true) String ids) {
        if (this.veJwTiaokeService.changeStatusByIds(ids.split(","), 0) > 0) {
            return Result.OK("操作成功!");
        }
        return Result.error("操作失败");
    }

    /**
     * 调课通知
     *
     * @return
     */
    @AutoLog(value = "调课信息-调课通知")
    @PostMapping("notice")
    @ApiOperation(value = "调课通知", notes = "调课信息-调课通知")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "subject", value = "标题", required = true),
            @ApiImplicitParam(name = "content", value = "内容", required = true),
            @ApiImplicitParam(name = "sendUserId", value = "收件人", required = true)
    })
    public Result<?> notice(String subject,
                            String content,
                            String sendUserId) {
        return Result.OK("发送成功!");
//        if(this.veJwTiaokeService.changeStatusByIds(ids.split(","),0)>0){
//            return Result.OK("操作成功!");
//        }
//        return Result.error("操作失败");
    }

//	/**
//	 * 通过id删除
//	 * @param id
//	 * @return
//	 */
//	@AutoLog(value = "调课信息-通过id删除")
//	@ApiOperation(value="通过id删除", notes="调课信息-通过id删除")
//	@PostMapping(value = "/delete")
//	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
//        if(veJwTiaokeService.removeById(id)){
//		    return Result.OK("删除成功!");
//        }
//        return Result.error("删除失败!");
//	}
//
//	/**
//	 * 批量删除
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "调课信息-批量删除")
//	@ApiOperation(value="批量删除", notes="调课信息-批量删除")
//	@PostMapping(value = "/deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		if(this.veJwTiaokeService.removeByIds(Arrays.asList(ids.split(",")))){
//		         return Result.OK("批量删除成功!");
//        }
//        return Result.error("批量删除失败!");
//	}

}
